const app = getApp();
var url = app.data.platFormUrl;
var pageNo = 1;
var pageSize = 10;
var queryName = "";
var currentCityCode = "";  //当前城市code(用于查询列表数据)
var currentCityCodeRoot = "";  //当前城市code的最顶级编码(用于查询省市区treeSelect)
var lat;                   //纬度
var lng;                   //经度
var city = require('../../utils/city.js');
var citySearch = require('../../utils/citySearchList.js');
var areaSearch = require('../../utils/areaInfo.js');
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
import Dialog from '@vant/weapp/dialog/dialog';
const WATERFALL_SOURCE = require('../../utils/waterfall_source.js');





var qqmapsdk;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    play: false,
    hotel: "",
    restaurant: "",
    categorySwiper: false,
    categoryFirstPageList: [], //第一页类目数据
    categorySecondPageList: [],//第二页类目数据
    adList: [], //首页广告轮播图
    merchantList: [],
    unitList: ["1", "2", "3"],
    picRoot: "https://",
    citySelected: '',
    cityListShow: false,
    inputListShow: false,
    historyListShow: false,
    citySearchTipListShow: false,
    show: false,
    citySearchKeyWord: "",
    hotCityData: [],
    cityData: {},
    citySearchData : {},
    _py: ["hot", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z"],
    scrollHeight: 0,
    hidden: true,
    city: '',
    currentCity: '',
    currentCityCode: '',
    displayCategoryStatus: 0,

    /**
     * 瀑布流
     */
    pageNo: 0,
    pageSrc: [],
    isEnd: false,
  },


  //点击首页商家
  hotCircleClick: function (event) {
    console.log(event)
    var tapId = event.currentTarget.id;
    var type = event.currentTarget.dataset.type;
    // 跳转到商家详情，0餐饮 非0其他商家
    if (type == 0) {
      let data = {};
      data.id = tapId;
      let rtnData = JSON.stringify(data);
      wx.navigateTo({
        url: '../../pages/detail/index?data=' + rtnData
      })
    } else {
      wx.navigateTo({
        url: '/pages/merchant/index?merchantId=' + tapId
      })
    }

  },

  /**
   * 首页下方 商家列表下拉刷新数据
   */
  scrollTolower: function () {
    console.info("------------分页数据了-----------");
    if (this.data.isHaveMore) {
      this.data.circleList = this.data.circleList.concat(this.data.moreBeauty)
      this.setData({
        circleList: this.data.circleList,
        isHaveMore: false
      })
    } else {
      wx.showToast({
        title: '没有更多了',
        icon: 'none',
        image: '',
        duration: 1000,
        mask: true,
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    }
  },


  onShow: function () {
    this.getTabBar().init();
    pageNo = 1;
    this.isDisplay();
  },

  /**
   * display category list
   */
  isDisplay: function(){
    let that = this;
    wx.request({
      url: url + '/pfCategoryApi/client/noAuth/isDisplayCategoryList',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.code == 200) {
          console.info(res.data.data);
          that.setData({
            displayCategoryStatus: res.data.data
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }
      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /***
   * 下拉刷新
   */
  onPullDownRefresh: function () {
    //console.info("-------------------下拉刷新--------------------");
    //wx.stopPullDownRefresh();

    wx.showNavigationBarLoading();
    console.info("刷新");
    this.setData({
      pageSrc: WATERFALL_SOURCE.source
    }, () => {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    })
  },
  /***
   * 上拉加载
   */
  onReachBottom: function () {
    console.info("-------------------上拉加载--------------------");
    pageNo = pageNo + 1;
    if(!this.data.isEnd){
      this.queryPageMerchant(pageNo, pageSize, lat, lng, this.data.currentCityCode);
    }
  },
  onChange(event) {
    this.setData({
      active: event.detail
    });
    var order = event.detail;
    if (0 == order) {
      // 首页
      // wx.redirectTo({
      //   url: '../../pages/index/index',
      // })
    } else if (1 == order) {
      // 我的订单
      // wx.redirectTo({
      //   url: '../../pages/order/index',
      // })
    } else if (2 == order) {
      // 个人中心
      // wx.redirectTo({
      //   url: '../../pages/mine/index',
      // })
    }
  },
  clickOther: function (options) {
    Dialog.alert({
      message: '当前栏目正在筹备中...敬请期待!'
    }).then(() => {
      // on close
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var th = this;
    th.setData({
      hotCityData: city.hot,
      cityData: city.all,
      citySearchData: citySearch.data
    })
    //定位用户当前位置(根据当前位置查询首页商家信息)
    this.userGetLocation();
    //查询广告
    this.initAd();
    //查询类目
    this.initCategory();
    //获取手机可视高度，设置商家菜单高度，塞满
    wx.getSystemInfo({
      success: function (res) {
        // 获取可使用窗口宽度
        let clientHeight = res.windowHeight;
        // 获取可使用窗口高度
        let clientWidth = res.windowWidth;
        // 算出比例
        let ratio = 750 / clientWidth;
        //手机型号
        let mobileModel = res.model;
        // 算出高度(单位rpx)
        let height = clientHeight * ratio;
        console.info("---------------------------------显示屏高度 : " + height + "--------------------------")
        //高度减去顶部和底部
        height = height - 54;
        if (mobileModel.indexOf("iPhone XR") != -1
          || mobileModel.indexOf("iPhone XS") != -1
          || mobileModel.indexOf("iPhone 11") != -1) {
          height = height - 50;
        }
        console.info("---------------------------------显示屏可视高度 : " + height + "--------------------------")
        console.info("-------------------" + mobileModel + "---------------");
        //设置高度
        th.setData({
          scrollHeight: height
        })

      }
    });
  },

  itemTap: function (e) {
    console.log(e)
    var tapId = e.detail.dataset.item.id;
    var type = e.detail.dataset.item.type;
    // 跳转到商家详情，0餐饮 非0其他商家
    if (type == 0) {
      let data = {};
      data.id = tapId;
      let rtnData = JSON.stringify(data);
      wx.navigateTo({
        url: '../../pages/detail/index?data=' + rtnData
      })
    } else {
      wx.navigateTo({
        url: '/pages/merchant/index?merchantId=' + tapId
      })
    }
  },

  //打开城市列表
  openCityList: function () {
    var th = this;
    th.setData({
      cityListShow: true,
      inputListShow: false,
      historyListShow: false,
      show: true
    });
  },

  userGetLocation: function () {
    let vm = this
    wx.getSetting({
      success: (res) => {
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        // 拒绝授权后再次进入重新授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          // console.log('authSetting:status:拒绝授权后再次进入重新授权', res.authSetting['scope.userLocation'])
          wx.showModal({
            title: '',
            content: '【灵动通】需要获取你的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none'
                })
                setTimeout(() => {
                  wx.navigateBack()
                }, 1500)
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    // console.log('dataAu:success', dataAu)
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation(dataAu)
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none'
                      })
                      setTimeout(() => {
                        wx.navigateBack()
                      }, 1500)
                    }
                  }
                })
              }
            }
          })
        }
        // 初始化进入，未授权
        else if (res.authSetting['scope.userLocation'] == undefined) {
          // console.log('authSetting:status:初始化进入，未授权', res.authSetting['scope.userLocation'])
          //调用wx.getLocation的API
          vm.getLocation(res)
        }
        // 已授权
        else if (res.authSetting['scope.userLocation']) {
          // console.log('authSetting:status:已授权', res.authSetting['scope.userLocation'])
          //调用wx.getLocation的API
          vm.getLocation(res)
        }
      }
    })
  },

  // 微信获得经纬度
  getLocation: function (userLocation) {
    let vm = this
    wx.getLocation({
      type: "gcj02",
      success: function (res) {
        //console.log('getLocation:success', res)
        var latitude = res.latitude
        var longitude = res.longitude
        lat = latitude;
        lng = longitude;
        vm.getLoc(latitude, longitude)
      },
      fail: function (res) {
        // console.log('getLocation:fail', res)
        if (res.errMsg === 'getLocation:fail:auth denied') {
          wx.showToast({
            title: '拒绝授权',
            icon: 'none'
          })
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
          return
        }
        if (!userLocation || !userLocation.authSetting['scope.userLocation']) {
          vm.getUserLocation()
        } else if (userLocation.authSetting['scope.userLocation']) {
          wx.showModal({
            title: '',
            content: '请在系统设置中打开定位服务',
            showCancel: false,
            success: result => {
              if (result.confirm) {
                wx.navigateBack()
              }
            }
          })
        } else {
          wx.showToast({
            title: '授权失败',
            icon: 'none'
          })
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        }
      }
    })
  },

  queryPageMerchant: function (current, size, latitude, longitude, currentCityCode) {
    var _that = this;
    wx.request({
      url: url + '/MerchantApi/client/noAuth/listPageMerchantForIndex',
      method: 'POST',
      data: { latitude: latitude, longitude: longitude, pageNo: current, pageSize: size, cityCode: currentCityCode },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.code == 200) {
          if (current == 1) {
            //_that.setData({
              //merchantList: res.data.data.pageList,
            //})
            //组装数据 渲染瀑布流
            var list = [];
            for (var i = 0; i < res.data.data.pageList.length; i++){
              var obj = new Object();
              obj.title = res.data.data.pageList[i].name;
              obj.imgUrl = 'https://' + res.data.data.pageList[i].coverIcon;
              obj.imgW = res.data.data.pageList[i].coverWidth;
              obj.imgH = res.data.data.pageList[i].coverHeight;
              obj.id = res.data.data.pageList[i].id;
              obj.type = res.data.data.pageList[i].type;
              list[i] = obj;
            }
            _that.setData({
              pageSrc: list
            });
            if (res.data.data.pageList.length < 10){
              _that.setData({
                isEnd: true
              });
            }
          } else {
            //_that.setData({
              //merchantList: _that.data.merchantList.concat(res.data.data.pageList)
            //})
            if (res.data.data.pageList.length > 0){
              let _pageNo = _that.data.pageNo + 1;
              var list = [];
              for (var i = 0; i < res.data.data.pageList.length; i++) {
                var obj = new Object();
                obj.title = res.data.data.pageList[i].name;
                obj.imgUrl = 'https://' + res.data.data.pageList[i].coverIcon;
                obj.imgW = res.data.data.pageList[i].coverWidth;
                obj.imgH = res.data.data.pageList[i].coverHeight;
                obj.id = res.data.data.pageList[i].id;
                obj.type = res.data.data.pageList[i].type;
                list[i] = obj;
              }
              _that.setData({
                pageNo: _pageNo,
                pageSrc: list
              });
            }
            //显示底线
            if (res.data.data.pageList.length < 10) {
              _that.setData({
                isEnd: true
              });
            }
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }
      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })
  },

  initAd: function () {
    var _that = this;
    wx.request({
      url: url + '/pfAdvertisementApi/client/noAuth/randomListPfAdvertisement',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.code == 200) {
          _that.setData({
            adList: res.data.data
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }
      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })
  },

  initCategory: function () {
    var _that = this;
    //临时方案-请求可视首页类目信息
    wx.request({
      url: url + '/pfCategoryApi/client/noAuth/listPfCategory',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res);
        if (res.data.code == 200) {
          _that.setData({
            categoryFirstPageList: res.data.data.slice(0, 10)
          })
          if (res.data.data.length > 10) {
            var secondList = res.data.data.slice(10, res.data.data.length);
            if (res.data.data.length == 20) {
              secondList[9].categoryIcon = "../../icon/7.png";
              secondList[9].categoryName = "更多";
            }
            //代表有两页
            _that.setData({
              categorySwiper: true,
              categorySecondPageList: secondList
            })
          }

        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }
      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })
  },

  onSearch: function (e) {
    var th = this;
    pageNo = 1;
    pageSize = 10;
    queryName = e.detail;
    //console.info(e.detail);
    //th.queryTable(pageNo, pageSize, queryName, queryType, currentCityCode, lat, lng, false, "");
  },

  //选择城市
  selectCity: function (e) {
    var th = this;
    var dataset = e.currentTarget.dataset;
    th.setData({
      citySelected: dataset.fullname,
      city: dataset.fullname,
      cityListShow: false,
      inputListShow: false,
      historyListShow: true,
      location: {
        latitude: dataset.lat,
        longitude: dataset.lng
      },
      show: false
    });
    //按选中城市或者区县刷新列表
    console.log("选择城市/县区 code:" + dataset.code);
    currentCityCode = dataset.code;
    currentCityCodeRoot = dataset.root;
    pageNo = 1;
    th.queryPageMerchant(pageNo, pageSize, lat, lng, currentCityCode);

  },

  citySearchOnFocus(e) {
    this.setData({
      cityListShow: false,
      citySearchTipListShow: true
    });
  },

  citySearchOnBlur(e) {
    this.setData({
      cityListShow: true,
    });
  },

  citySearchOnChange(e) {
    this.setData({
      citySearchKeyWord: e.detail,
    });
  },

  onClose() {
    this.setData({ show: false });
  },

  //滑动选择城市
  tMove: function (e) {
    var y = e.touches[0].clientY,
      offsettop = e.currentTarget.offsetTop;

    //判断选择区域,只有在选择区才会生效
    if (y > offsettop) {
      var num = parseInt((y - offsettop) / 12);
      this.setData({
        showPy: this.data._py[num]
      })
    };
  },

  //触发全部开始选择
  tStart: function () {
    this.setData({
      hidden: false
    })
  },

  //触发结束选择
  tEnd: function () {
    this.setData({
      hidden: true,
      scrollTopId: this.data.showPy
    })
  },

  //获取文字信息
  getPy: function (e) {
    this.setData({
      hidden: false,
      showPy: e.target.id,
    })
    console.info("*****************" + e.target.id);
  },

  setPy: function (e) {
    this.setData({
      hidden: true,
      scrollTopId: this.data.showPy
    })
    console.log("-----------------" + this.data.showPy + "-----------------");
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 行业点击
   */
  categoryClick: function (e) {
    console.info(e);
    var toUrl = "";
    if (e.currentTarget.dataset.code == "CESHI9") {
      toUrl = "/pages/category/index";
    } else {
      toUrl = "/pages/shop/index";
    }
    console.info(e.currentTarget.dataset.code);
    wx.navigateTo({
      url: toUrl + '?city=' + this.data.currentCity + "&cityCode=" + this.data.currentCityCode + "&lat=" + lat + "&lng=" + lng + "&type=" + e.currentTarget.dataset.code + "&firstId=" + e.currentTarget.dataset.id + "&secondId="
    })
  },

  toCanyin: function () {
    wx.navigateTo({
      url: '/pages/shop/index?city=' + this.data.currentCity + "&cityCode=" + this.data.currentCityCode + "&lat=" + lat + "&lng=" + lng + "&type=CANYIN"
    })
  },


  getLoc: function (latitude, longitude) {
    var th = this;
    qqmapsdk = new QQMapWX({
      //申请的腾讯地图位置服务密钥
      key: 'GSEBZ-FAFWX-PFD46-TEB2O-O2RE2-A5BGL'
    });

    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (addressRes) {
        const result = addressRes.result;
        console.log("当前所在:");
        console.log(addressRes.result);
        th.setData({
          citySelected: addressRes.result.address_component.city,
          city: addressRes.result.address_component.city,
          currentCity: addressRes.result.address_component.city,
          currentCityCode: addressRes.result.ad_info.city_code.replace(addressRes.result.ad_info.nation_code, "")
        })
        //查询首页商家 显示由近到远的商家(不论类型)
        th.queryPageMerchant(pageNo, pageSize, latitude, longitude, th.data.currentCityCode);

      }
    })
  },

  test: function () {
    console.info("fuck");
  },


  //首页菜单功能  有需要可以打开
  /*changePlay() {
    let flag = !this.data.play;
    this.setData({
      play: flag
    });
    //start title
    let titleOpenAn = wx.createAnimation({
      duration: 300,
      timingFunction: 'forwards',
      delay: 0,
      transformOrigin: '50% 50% 0'
    });
    titleOpenAn.opacity(0).step();
    this.setData({
      titleOpenAn: titleOpenAn.export()
    });
    let titleCloseAn = wx.createAnimation({
      duration: 300,
      timingFunction: 'forwards',
      delay: 0,
      transformOrigin: '50% 50% 0'
    });
    titleCloseAn.opacity(1).step();
    this.setData({
      titleCloseAn: titleCloseAn.export()
    });
    //end title
    // start 第一条line
    let line1OpenAn = wx.createAnimation({
      duration: 300,
      timingFunction: 'forwards',
      delay: 0,
      transformOrigin: '50% 50% 0'
    });
    line1OpenAn.translateY(12).rotate(45).scale(1.4, 1).step();
    this.setData({
      line1OpenAn: line1OpenAn.export()
    });
    let line1CloseAn = wx.createAnimation({
      duration: 300,
      timingFunction: 'forwards',
      delay: 0,
      transformOrigin: '12rpx 50%'
    });
    line1CloseAn.translateY(0).rotate(0).scale(1, 1).step();
    this.setData({
      line1CloseAn: line1CloseAn.export()
    });
    //end 第一条line

    // start 第二条line
    let line2OpenAn = wx.createAnimation({
      duration: 300,
      timingFunction: 'forwards',
      delay: 0,
      transformOrigin: '100% 0'
    });
    line2OpenAn.translateY(-6.5).translateX(-1).rotate(-45).scale(1.4, 1).step();
    this.setData({
      line2OpenAn: line2OpenAn.export()
    });

    let line2CloseAn = wx.createAnimation({
      duration: 300,
      timingFunction: 'forwards',
      delay: 0,
      transformOrigin: '46rpx 50%'
    });
    line2CloseAn.translateY(0).rotate(0).scale(1, 1).step();
    this.setData({
      line2CloseAn: line2CloseAn.export()
    });
    //end 第二条line

    //start 第一个按钮
    let btn1Open = wx.createAnimation({
      duration: 300,
      timingFunction: 'forwards',
      delay: 0,
      transformOrigin: '100% 0'
    });
    btn1Open.translateX(-60).opacity(1).step();
    this.setData({
      btn1Open: btn1Open.export()
    });

    let btn1Close = wx.createAnimation({
      duration: 300,
      timingFunction: 'forwards',
      delay: 0,
      transformOrigin: '46rpx 50%'
    });
    btn1Close.translateX(0).opacity(0).step();
    this.setData({
      btn1Close: btn1Close.export()
    });
    //end 第一个按钮
    //start 第二个按钮
    let btn2Open = wx.createAnimation({
      duration: 500,
      timingFunction: 'forwards',
      delay: 0,
      transformOrigin: '100% 0'
    });
    btn2Open.translateX(-120).opacity(1).step();
    this.setData({
      btn2Open: btn2Open.export()
    });

    let btn2Close = wx.createAnimation({
      duration: 500,
      timingFunction: 'forwards',
      delay: 0,
      transformOrigin: '46rpx 50%'
    });
    btn2Close.translateX(0).opacity(0).step();
    this.setData({
      btn2Close: btn2Close.export()
    });
    //end 第二个按钮
    //start 第三个按钮
    let btn3Open = wx.createAnimation({
      duration: 700,
      timingFunction: 'forwards',
      delay: 0,
      transformOrigin: '100% 0'
    });
    btn3Open.translateX(-180).opacity(1).step();
    this.setData({
      btn3Open: btn3Open.export()
    });

    let btn3Close = wx.createAnimation({
      duration: 700,
      timingFunction: 'forwards',
      delay: 0,
      transformOrigin: '46rpx 50%'
    });
    btn3Close.translateX(0).opacity(0).step();
    this.setData({
      btn3Close: btn3Close.export()
    });
    //end 第三个按钮
    //start 第四个按钮
    let btn4Open = wx.createAnimation({
      duration: 700,
      timingFunction: 'forwards',
      delay: 0,
      transformOrigin: '100% 0'
    });
    btn4Open.translateX(-240).opacity(1).step();
    this.setData({
      btn4Open: btn4Open.export()
    });

    let btn4Close = wx.createAnimation({
      duration: 700,
      timingFunction: 'forwards',
      delay: 0,
      transformOrigin: '46rpx 50%'
    });
    btn4Close.translateX(0).opacity(0).step();
    this.setData({
      btn4Close: btn4Close.export()
    });
    //end 第四个按钮
  }*/

  
 
})